﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WorldBankBBS.Security;

namespace WorldBankBBS.Data
{
    public partial class Message
    {
        public static void MarkReadForUser(Guid messageUID, Guid userUID)
        {
            using (var mh = new ModelHelper())
            {
                mh.BeginNewContext();

                var mu = mh.Context.MessageUsers.FirstOrDefault(x => x.MessageUID == messageUID && x.UserUID == userUID);

                if (mu == null)
                {
                    mu = new MessageUser
                    {
                        IsHidden = false,
                        IsRead = true,
                        MessageUID = messageUID,
                        UserUID = userUID,
                        ReadOn = DateTime.UtcNow,
                    };

                    mh.Context.MessageUsers.Add(mu);
                }
                else
                {
                    if (!mu.IsRead)
                    {
                        mu.IsRead = true;
                        mu.ReadOn = DateTime.UtcNow;
                    }
                }

                var threadUID = mh.Context.Messages.FirstOrDefault(m => m.MessageUID == messageUID).ThreadUID;

                var tu = mh.Context.ThreadUsers.FirstOrDefault(x => x.UserUID == userUID && x.ThreadUID == threadUID);

                if (tu == null)
                {
                    tu = new ThreadUser
                    {
                        ThreadUID = threadUID,
                        UserUID = userUID,
                        LastMessageReadUID = messageUID,
                    };

                    mh.Context.ThreadUsers.Add(tu);
                }
                else
                {
                    tu.LastMessageReadUID = messageUID;
                }

                mh.Context.SaveChanges();
            }
        }
    }
}
